package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class LoginApiController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserInfoService userInfoService;
    //登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //校验 用户名&密码 不能为空
        if (null != userInfo){
            if (StringUtils.isEmpty(userInfo.getLoginName())){
                return Result.fail().message("用户名不能为空");
            }
            if (StringUtils.isEmpty(userInfo.getPasswd())){
                return Result.fail().message("密码不能为空");
            }
        }else {
            return Result.fail().message("不能为空");
        }
        //校验 用户名&密码 是否正确
        userInfo = userInfoService.checkLogin(userInfo);
        if (null != userInfo){
            //用户名及密码是正确的
            //颁发令牌
            String token = UUID.randomUUID().toString().replaceAll("-","");
            String nickName = userInfo.getNickName();
            Map map = new HashMap();
            map.put("token",token);
            map.put("nickName",nickName);
            //保存用户信息到redis
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + token,
                    userInfo.getId().toString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        }else {
            return Result.fail().message("用户名或密码错误");
        }
    }

    //退出登录
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX
        + request.getHeader("token"));
        return Result.ok();
    }

}
